import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/common/HelpDocItem.dart';
import 'package:ichinesereader/pages/helpDoc/helpItemDetails.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import '../../themes/appTheme.dart';
import '../../themes/pageStyles.dart';
import 'package:http/http.dart' as http;

class HelpDocsHome extends StatefulWidget {
  static const String routeName = '/docs';

  @override
  State<HelpDocsHome> createState() => _HelpDocsHomeState();
}

class _HelpDocsHomeState extends State<HelpDocsHome> {
  var helpDocs = <HelpDocItem>[];
  final box = Hive.box('appconfig');
  int _userType = 1;
  int _localNum = 0;
  HelpDocItem currentHelpDocItem = HelpDocItem();
  final PageStyles _pageStyles = PageStyles();
  String _currentTitle = '';

  @override
  void initState() {
    currentHelpDocItem.helpItems = <HelpDocItem>[];

    _localNum = box.get('locale') ?? 0;

    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin) {
      _userType = 0;
    }
    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher) {
      _userType = 1;
    }
    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student) {
      _userType = 2;
    }
    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual) {
      _userType = 3;
    }
    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Parent) {
      _userType = 4;
    }
    http
        .get(Uri.parse('https://resources.ichinesereader.com/help/help.json'))
        .then((response) {
      if (response.statusCode == 200) {
        setState(() {
          helpDocs = helpDocItemFromJson(utf8.decode(response.bodyBytes))
              .where((element) => element.type == _userType)
              .toList();
          currentHelpDocItem = helpDocs[0];

          _currentTitle = currentHelpDocItem.title != null
              ? currentHelpDocItem.title!.en.toString()
              : '';
          if (_localNum == 1) {
            _currentTitle = currentHelpDocItem.title!.cn != null &&
                    currentHelpDocItem.title!.cn != ""
                ? currentHelpDocItem.title!.cn.toString()
                : _currentTitle;
          }
          if (_localNum == 2) {
            _currentTitle = currentHelpDocItem.title!.tc != null &&
                    currentHelpDocItem.title!.tc != ""
                ? currentHelpDocItem.title!.tc.toString()
                : _currentTitle;
          }
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final isMediumScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenMediumSize;

    return Container(
      decoration: _pageStyles.pageBoxDecoration(),
      child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: CustomAppBar(title: 'User Manual'.tr),
          body: isMediumScreen
              ? Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 21.0),
                      width: 420,
                      height: Get.height - 48,
                      margin: EdgeInsets.fromLTRB(12.0, 30.0, 12.0, 30.0),
                      decoration: BoxDecoration(
                        color: Get.isDarkMode
                            ? AppTheme.colors.darkTheme2
                            : Colors.black.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(3.0),
                      ),
                      child: SingleChildScrollView(
                        child: helpDocs.isNotEmpty
                            ? ListView.builder(
                                scrollDirection: Axis.vertical,
                                shrinkWrap: true,
                                itemCount: helpDocs.length,
                                itemBuilder: (context, index) {
                                  String _title = helpDocs[index].title != null
                                      ? helpDocs[index].title!.en.toString()
                                      : '';
                                  if (_localNum == 1) {
                                    _title = helpDocs[index].title!.cn !=
                                                null &&
                                            helpDocs[index].title!.cn != ""
                                        ? helpDocs[index].title!.cn.toString()
                                        : _title;
                                  }
                                  if (_localNum == 2) {
                                    _title = helpDocs[index].title!.tc !=
                                                null &&
                                            helpDocs[index].title!.tc != ""
                                        ? helpDocs[index].title!.tc.toString()
                                        : _title;
                                  }

                                  return ListTile(
                                    //need customize the selected color
                                    selectedTileColor: Colors.black,
                                    selectedColor: Colors.blueAccent,
                                    leading: Container(
                                      width: 39.0,
                                      padding: EdgeInsets.all(4.5),
                                      decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColor
                                            : Colors.black.withOpacity(0.1),
                                      ),
                                      child: Container(
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColorDark
                                              : AppTheme.colors.pinkBtn
                                                  .withOpacity(0.8),
                                        ),
                                        child: Text(
                                          '${(index + 1).toString()}',
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              color: Get.isDarkMode
                                                  ? Colors.black
                                                  : Colors.white),
                                        ),
                                      ),
                                    ),
                                    title: Text(
                                      _title,
                                      style: TextStyle(
                                          fontSize: 15.0,
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColorDark
                                              : Get.theme.primaryColorLight),
                                    ),
                                    onTap: () {
                                      setState(() {
                                        currentHelpDocItem = helpDocs[index];

                                        _currentTitle =
                                            helpDocs[index].title != null
                                                ? helpDocs[index]
                                                    .title!
                                                    .en
                                                    .toString()
                                                : '';
                                        if (_localNum == 1) {
                                          _currentTitle = helpDocs[index]
                                                          .title!
                                                          .cn !=
                                                      null &&
                                                  helpDocs[index].title!.cn !=
                                                      ""
                                              ? helpDocs[index]
                                                  .title!
                                                  .cn
                                                  .toString()
                                              : _currentTitle;
                                        }
                                        if (_localNum == 2) {
                                          _currentTitle = helpDocs[index]
                                                          .title!
                                                          .tc !=
                                                      null &&
                                                  helpDocs[index].title!.tc !=
                                                      ""
                                              ? helpDocs[index]
                                                  .title!
                                                  .tc
                                                  .toString()
                                              : _currentTitle;
                                        }
                                      });
                                    },
                                  );
                                },
                              )
                            : Text('Coming soon ...'.tr),
                      ),
                    ),
                    Expanded(
                        child: Container(
                      margin: _pageStyles.mainContainerPageEdgeInsets(),
                      padding: EdgeInsets.all(21.0),
                      decoration: BoxDecoration(
                        color: Get.isDarkMode
                            ? AppTheme.colors.darkTheme2
                            : Colors.white.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(3.0),
                      ),
                      child: SingleChildScrollView(
                        primary: false,
                        scrollDirection: Axis.vertical,
                        child: Column(children: [
                          Container(
                            padding: EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(30.0),
                              color: Get.isDarkMode
                                  ? Colors.black
                                  : Colors.black.withOpacity(0.1),
                            ),
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 6.0, horizontal: 45.0),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(30.0),
                                color: Get.isDarkMode
                                    ? Colors.black
                                    : AppTheme.colors.purpleBtn,
                              ),
                              child: Column(
                                children: [
                                  Text(
                                    _currentTitle,
                                    style: TextStyle(
                                        letterSpacing: 1,
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColorDark
                                            : Colors.white,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 21.0),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Container(
                            child: currentHelpDocItem.helpItems!.isNotEmpty
                                ? Column(
                                    children: buildHelpCards(
                                        currentHelpDocItem.helpItems
                                            as List<HelpDocItem>,
                                        _localNum))
                                : Text(""),
                          )
                        ]),
                      ),
                    )),
                  ],
                )
              : Column(children: [
                  Container(
                    width: double.infinity,
                    height: Get.height - 72,
                    margin: EdgeInsets.all(12.0),
                    decoration: BoxDecoration(
                      color: Get.isDarkMode
                          ? AppTheme.colors.darkTheme2
                          : Colors.black.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(6.0),
                    ),
                    child: helpDocs.length > 0
                        ? ListView.builder(
                            shrinkWrap: true,
                            itemCount: helpDocs.length,
                            itemBuilder: (context, index) {
                              String _title = helpDocs[index].title != null
                                  ? helpDocs[index].title!.en.toString()
                                  : '';
                              if (_localNum == 1) {
                                _title = helpDocs[index].title!.cn != null &&
                                        helpDocs[index].title!.cn != ""
                                    ? helpDocs[index].title!.cn.toString()
                                    : _title;
                              }
                              if (_localNum == 2) {
                                _title = helpDocs[index].title!.tc != null &&
                                        helpDocs[index].title!.tc != ""
                                    ? helpDocs[index].title!.tc.toString()
                                    : _title;
                              }
                              return ListTile(
                                trailing: Icon(Icons.more_vert,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Get.theme.primaryColorLight),
                                leading: Container(
                                  width: 39.0,
                                  padding: EdgeInsets.all(4.5),
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColor
                                        : Colors.black.withOpacity(0.1),
                                  ),
                                  child: Container(
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Get.isDarkMode
                                          ? Get.theme.primaryColorDark
                                          : AppTheme.colors.pinkBtn
                                              .withOpacity(0.8),
                                    ),
                                    child: Text(
                                      '${(index + 1).toString()}',
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Get.isDarkMode
                                              ? Colors.black
                                              : Colors.white),
                                    ),
                                  ),
                                ),
                                title: Text(
                                  _title,
                                  style: TextStyle(
                                      fontSize: 15.0,
                                      color: Get.isDarkMode
                                          ? Get.theme.primaryColorDark
                                          : Get.theme.primaryColorLight),
                                ),
                                onTap: () {
                                  setState(() {
                                    currentHelpDocItem = helpDocs[index];
                                  });

                                  if (isMediumScreen) {
                                  } else {
                                    Get.to(
                                      () => HelpItemDetails(
                                          helpItem: helpDocs[index],
                                          localNum: _localNum),
                                    );
                                  }
                                },
                              );
                            },
                          )
                        : Text('Coming soon ...'.tr),
                  ),
                ])),
    );
  }
}
